package com.see.network.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.google.inject.Inject;
import com.see.domain.model.GoogleObject;
import com.see.domain.model.StockDetail;
import com.see.network.api.StockDetailParser;
import com.see.util.MarketMapping;

public class StockDetailGoogleFinaceParserImpl implements StockDetailParser {

    private final HtmlReader htmlReader;

    @Inject
    public StockDetailGoogleFinaceParserImpl(HtmlReader htmlReader) {
        this.htmlReader = htmlReader;
    }

    public Collection<StockDetail> parse(String googleUrlString) {

        String result = htmlReader.readHtml(googleUrlString, false);
        result = result.replaceAll("//", "");
        Gson gson = new Gson();
        GoogleObject[] googleObjects = gson.fromJson(result, GoogleObject[].class);
        List<StockDetail> detailList = new ArrayList<StockDetail>();
        for (GoogleObject googleObject : googleObjects) {
            detailList.add(convert(googleObject));
        }

        return detailList;
    }

    private StockDetail convert(GoogleObject googleObject) {
        StockDetail stockDetail = new StockDetail();
        stockDetail.setSymbol(googleObject.getT() + "." + getMarketMapping(googleObject));
        stockDetail.setPrice(Double.valueOf(googleObject.getL()));
        return stockDetail;
    }

    private String getMarketMapping(GoogleObject googleObject) {
        String market = MarketMapping.getMarketMapping(googleObject.getE()).toString();
        if ("".equals(market))
            market = googleObject.getE();

        return market;
    }

}
